package com.itboy.message.email.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itboy.common.exception.CustomException;

import org.springframework.stereotype.Service;
import com.itboy.message.email.domain.MsgEmailConfig;
import com.itboy.message.email.mapper.MsgEmailConfigMapper;
import com.itboy.message.email.vo.MsgEmailConfigVo;
import com.itboy.message.email.service.IMsgEmailConfigService;

/**
 * 邮箱配置Service业务层处理
 *
 * @author gssong
 * @date 2021-07-09
 */
@Service
public class MsgEmailConfigServiceImpl extends ServiceImpl<MsgEmailConfigMapper, MsgEmailConfig> implements IMsgEmailConfigService {

	@Override
	public boolean sendEmail(MsgEmailConfigVo msgEmailConfigVo) {
		MsgEmailConfig msgEmailConfig = this.baseMapper.selectList(null).get(0);
		if (ObjectUtil.isNull(msgEmailConfig)) {
			throw new CustomException("请先配置，再操作");
		}
		// 封装
		MailAccount account = new MailAccount();
		// 设置用户
		String user = msgEmailConfig.getFromUser().split("@")[0];
		account.setUser(user);
		account.setHost(msgEmailConfig.getHost());
		account.setPort(Integer.parseInt(msgEmailConfig.getPort()));
		account.setAuth(true);
		account.setPass(msgEmailConfig.getPass());
		account.setFrom(msgEmailConfig.getUser() + "<" + msgEmailConfig.getFromUser() + ">");
		// ssl方式发送
		account.setSslEnable(true);
		// 使用STARTTLS安全连接
		account.setStarttlsEnable(true);
		String content = msgEmailConfigVo.getContent();
		// 发送
		try {
			int size = msgEmailConfigVo.getTos().size();
			Mail.create(account)
				.setTos(msgEmailConfigVo.getTos().toArray(new String[size]))
				.setTitle(msgEmailConfigVo.getSubject())
				.setContent(content)
				.setHtml(true)
				//关闭session
				.setUseGlobalSession(false)
				.send();
			return true;
		} catch (Exception e) {
			throw new CustomException(e.getMessage());
		}
	}
}
